/*
 *
 * System2 Simulation Framework
 * Copyright (C) 2011 - 2012 Jacob Dawid
 * jacob.dawid@googlemail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "atom.h"
#include <iostream>

namespace System2 {
    Atom::Atom(int id, Context *context, Component *component)
        : QThread(), Serializable() {
        m_id = id;
        m_context = context;
        m_component = component;
        m_signalBundle = 0;
        m_state = Waiting;
        m_stateSemaphore = new QSemaphore(1);
    }

    Atom::~Atom() {
        delete m_stateSemaphore;
    }

    Atom::State Atom::state() {
        SemaphoreScopeLocker locker(m_stateSemaphore);
        (void)locker;
        return m_state;
    }

    QString Atom::serialize() {
        return QString("<Job id=\"%1\">").arg(id())
                + m_context->serialize()
                + m_component->serialize()
                + m_signalBundle->serialize()
                + "</Job>";
    }

    bool Atom::unserialize(const QString& data) {
        (void)data;
        return true;
    }

    void Atom::execute() {
        QMetaObject::invokeMethod(this, "start");
    }

    void Atom::deposit() {
        m_state = Deposited;
        emit deposited();
    }

    void Atom::makeDependentOf(int atomId) {
        if(!isDependentOf(atomId)) {
            m_dependencies.push_back(atomId);
        }
    }

    bool Atom::isDependentOf(int atomId) {
        return m_dependencies.contains(atomId);
    }

    bool Atom::isIndependent() {
        return m_dependencies.isEmpty();
    }

    void Atom::setSignalBundle(SignalBundle *signalBundle) {
        m_signalBundle = signalBundle;
    }

    SignalBundle *Atom::signalBundle() {
        return m_signalBundle;
    }

    int Atom::id() {
        return m_id;
    }

    void Atom::run() {
        m_state = Running;
        m_component->process(m_context, m_signalBundle);
        m_state = Finished;
    }
}
